/**
 * 基于Jquery自定义表格控件
 * @author wonderful-wudaohong wuketidai@foxmail.com
 * @create 20131008
 * @version 3.0
 * @update 20180823
 * @description 基于jquery插件实现，完全自主垒码，所有代码全系个人手写纯净无COPY(UUID生成代码除外(^_^))
 * @1.0.3增加goPage跳转页操作(同时修复小键盘输入无效问题)，增加动态消息提示，formatter回调函数增加行对象参数 wonderful 20140425。
 * @1.1.0增加行编辑功能 wonderfulHongXin 20180116
 * @1.2.0增加行编辑验证功能 wonderfulHongXin 20180129
 * @2.0 整体风格重大改版，部分功能细节优化 杨骁
 * @2.1 增加列宽可通过拖拽进行改变的功能 wonderfulHongXin 20180425
 * @2.2 增加自定义排序功能 wonderfulHongXin 20180515
 * @2.3 增加gridData非异步数据加载方式 杨骁 20180823
 * @3.0  wonderfulHongXin 20180823 增加了子表功能，理论上可以支持无限级子表；
 * 增加了编辑状态的格式化，并增加了添加行、编辑行、取消编辑行等状态在格式回调函数里进行识别。
 * 增加了编辑输入对mydate97日历控件的支持
 */
/**
 * $("#gridDivId").wdfGrid("init",gridOpt); //初始化grid
 * $("#gridDivId").wdfGrid("getEditInput")(rowObj,inputId);//获取指定grid编辑行的某一个编辑输入框对象
 * $("#gridDivId").wdfGrid("editRows")(editRows,isSave,isOnlyVal);//编辑行切换，参数：editRows,需要编辑的行对象数组，[rowObj];
 *                                                                                 isSave，是否把编辑行切换为非编辑行并保存输入框内的值到行数据rowData,取值范围true|false。
 *                                                                                 isOnlyval,仅仅只触发编辑行的验证功能而不进行任何操作，取值范围true|false。
 *$("#gridDivId").wdfGrid("getAllRows"); //返回所有行数据 [rowData];
 * $("#gridDivId").wdfGrid("getAllRowObjs"); //返回所有行对象 [rowObj];
 * $("#gridDivId").wdfGrid("getSelRows"); //返回选中的行数据 [rowData];
 * $("#gridDivId").wdfGrid("getSelRowObjs"); //返回选中的行对象 [rowObj];
 * $("#gridDivId").wdfGrid("getNotSelRows"); //返回未选中的行数据 [rowData];
 * $("#gridDivId").wdfGrid("getRowDatasByDK",{key:"",value:""}); //根据对应的键和值返回行数据[rowData]，如：行数据有属性name,
 * 则$("#gridDivId").wdfGrid("getRowDatasByDK",{key:"name",value:"张三"}); 可获取grid已显示的界面上名称为张三的所有行。
 * $("#gridDivId").wdfGrid("reload",gridOpt)重新加grid数据。
 * $("#gridDivId").wdfGrid("addRows",gridOpt)(rowDatas,isAsc); //添加行，rowDatas 行数据数组[rowData],isAsc 添加顺序是正序或倒序，取值范围true|false。
 * $("#gridDivId").wdfGrid("removeRows")(rowDatas); //删除行，rowDatas 行数据数组[rowData]。
 * $("#gridDivId").wdfGrid("clearRows"); //清除所有行
 */
(function () {
    var opt = {
        title: "test",// 表格标题名
        width: 1024,// 表格宽度
        height: 600,// 表格高度
        autoWidth: false,// 是否自适应宽度
        autoHeight: false,//是否自适应外部容器高度
        autoContentHeight:false,//是否自适应内容高度，优先级低于autoHeight。
        isSubGrid:false,//是否为子表
        colFixed: false,//固定列宽如果列宽固定可灵活设置列宽度，否则所有列将填充满表格最大宽度,所有列的auto宽度将失效并导致控件异常。
        className: "test",// 表格样式类名
        loadMsg: "正在加载数据请稍等",// 表格加载显示信息
        checkbox: true,//是否显示选中按钮
        isMulitCheck: false,//是支持多选
        param:{},//要请求的参数
        delayLoad: 500,//在表格元素填充后延迟表格数据加载，单位毫秒。
        root: "appSyss",//服务端返回的数据对象集合的属性名
        isRowNo: true,//是否显示行号
        keepPage: true,//调用重新加载数据函数后，保持当前页面，不跳转回第一页，每次调用要设置该属性一次
        isNotPage:false,//是否分页是false,否true。
        gridData:[],//非异步数据源
        columns: [
            {
                hidden: false,// 是否隐藏该列
                label: "子表",// 显示列名称
                name: "classify",// 列字段属性名
                width: "20px",// 列宽度
                gridOpt:"",//子表参数
                isSubColumn: true,//是否是子表操作列
                getParams:function(rowData){//子表请求后台数据时，需要代入的参数。
                    return {
                        name:rowData.name
                    };
                },
                click: function (rowData, rowTr, cell) {
                    $("#test").wdfGrid("subGrid")(rowData, rowTr, cell, opt);
                }
            }, {
                hidden: true,// 是否隐藏该列
                onShow: function () {//显示前执行,如果返回false则该列不显示

                    return true;
                },
                label: "id",// 显示列名称
                name: "test",// 列字段属性名
                width: "100px",// 列宽度
                order:{         //排序参数
                    name:"",//排序字段名称
                    label:"",//排序字段标签，用于鼠标抵达显示。
                    orderType:"ASC"//ASC | DESC 正序或倒序
                },
                formatter: function (columnValue) {
                }// 格式化
            }, {
                hidden: false,// 是否隐藏该列
                label: "品名",// 显示列名称
                name: "product",// 列字段属性名
                width: "300px",// 列宽度
                isOrder: true,// 是否排序
                isEditCol:true,//是否是编辑列
                editor:{
                	inputID:"",//输入对象的ID前缀，因为一个列表里，该输入框会随行数不断重复，故系统会在该值的基础上，
                	           //自动补充UUID后缀,该输入框ID建议在每一行对象里唯一。
                	inputType:"text",//text|comSel
                    isFormatter:true,//true|false 编辑模式下的格式化支持，该模式只支持text类型的输入框，
                    // 且该模式只支持普通格式化模式，即不触发isFmtHtml和isFmtJqueryObj模式的格式化。
                    // 切换到编辑模式触发对值的格式化后，再切换回非编辑模式，值不可逆！
                	comSelOpt:"",//通用下拉控件配置参数对象
                	isInitSel:false,//是否初始化comSel控件true/false
                	isTrigger:"change",//是否初始化后触发输入框的事件，change、click、blur、focus等。
                    isMyDate97:true,//是否支持mydate97选择
                    //mydate 97时间控件聚焦事件
                    myDate97Fouce:"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'});$(this).addClass('onFoucsWdate');",
                	valOpt:{//控件表单提交验证参数 wdfValiditon控件参数
                		
                	},
                	nameKey:"",//获取显示名称的键值
                	valKey:"",//获取值的键值
                	onKeyDown:function(rowObj,rowData,inputObj,gridObj){//键盘按下事件,当inputType为text时，该参数有效。
                		
                	},
                    onChange:function(rowObj,rowData,inputObj,gridObj){//输入内容改变事件,当inputType为text时，该参数有效。
                		
                	},
                    onClick:function(rowObj,rowData,inputObj,gridObj){//输入内容改变事件,当inputType为text时，该参数有效。

                    }
                },
               
                formatter: function (colValue,rowData,rowTr,rowTd,isAdd) {
                }// 格式化
            }, {
                hidden: false,// 是否隐藏该列
                label: "分类",// 显示列名称
                name: "classify",// 列字段属性名
                width: "400px",// 列宽度
                isOrder: true,// 是否排序
                formatter: function (columnValue, rowData) {
                }// 格式化

            },
            {
                hidden: false,// 是否隐藏该列
                label: "操作",// 显示列名称
                name: "classify",// 列字段属性名
                width: "400px",// 列宽度
                isBtnColumn: true,//是否是按钮操作列
                isOrder: true,// 是否排序
                isFmtHtml: true,//格式化是否返回html
                isFmtJqueryObj:true,//格式化是否返回jquery对象。
                formatter: function (columnValue, rowData, rowObj, rowTd, isAdd,isCancelEdit,isEdit) {
                    //return "<a src='"+basePath+"' target='_blank'/>";
                }
            }
        ],
        formatBtn: function (rowData, btns) {//按钮格式化,参数：(行数据/按钮集合),必须返回按钮集合
            btns[1].hidden = true;
            return btns;
        }
        //事件
        , event: {
        	rowAdded: function (opt, gridObj,rowData) {//行添加事件
            },
            loaded: function (opt, gridObj,rowDatas) {//grid数据加载完成后执行

            },
            readyLoad: function (opt, gridObj) {//grid数据加载前执行

            },
            onRowClick: function (rowData) {//行单击事件

            },
            dataFilter: function (rowDatas) {
                $(rowDatas).each(function () {
                    if (!this.vbc) {
                        this.vbc = {
                            name: "动态获取",
                            id: "动态获取"
                        };
                    }
                });
            },
            restGridHeight: function (gridHeight, gridObj) {//表格控件高度发生改变时触发，如果返回高度则表格控件则或根据返回的高度重置，否则则为默认高度(表格控件高度，表格控件对象)
                return gridHeight;
            }
        }
    };
    var isreload = 1;
  //事件传播处理
	function stopBubble(e)  
	   {  
	       if (e && e.stopPropagation)  
	           e.stopPropagation(); 
	       else 
	           window.event.cancelBubble=true;
	   };
	   
    var title;
    var width;
    
    $.fn.extend({
        wdfGrid: function (operate,option,isShowEdit) {
           // isreload = 1;
            var content = this;
            // 初始化表格
            if (operate == "init") {

                $(this).empty();
                var gridObj = $(this);
                gridObj.data("reqResult",null);
                var colLen = option.columns.length;
                if (option.checkBox)
                    colLen++;
                var theadTable = $("<thead></thead>");
                var headTable = $("<tr    id='" + this.attr("id")
                    + "_WdfGrid_HeadTable"
                    + "' width=" + (option.width) + "></tr>");
                headTable.addClass("WdfGrid_HeadTable");
                //滚动行容器
                var scrollDiv = $("<div id='" + this.attr("id") + "_WdfGrid_ScrollDiv' class='WdfGrid_ScrollDiv'></div>");
                var gridShouqi_btn = $("<div class='gridShouqi_btn' onclick='slideScrollDiv(this)'></div>").appendTo(gridObj);
                var gridZhankai_btn = $("<div class='gridZhankai_btn' onclick='slideDownScrollDiv(this)'></div>").appendTo(gridObj);

                //行容器
                var rowContent = $("<table   id='" + this.attr("id") + "_WdfGrid_RowContent" + "' width=" + (option.width) + "></table>");
                rowContent.addClass("WdfGrid_RowContent");
                var tableBox = $("<div></div>");
                tableBox.append(rowContent);
                scrollDiv.append(tableBox);
                theadTable.append(headTable);
                rowContent.append(theadTable);
                wdfTableWidth = 0;
                $(option.columns).each(function (i) {
                    if (this.hidden)
                        return;
                    //wdfTableWidth+=parseInt(this.width.replace(/(px|PX|Px|pX)+/,""));

                });
                //固定列宽
                if (option.colFixed) {
                    //加上chekBox列的宽
                    if (option.checkBox)
                        wdfTableWidth += 22;
                    rowContent.attr("width", wdfTableWidth);
                    this.css("width", option.width);
                }
                //如果为自适应宽度
                else if (option.autoWidth || option.autoHeight) {
                    if (option.autoWidth) {
                        this.css("width", this.parent().width());
                        rowContent.attr("width", rowContent.parent().width() - 2);
                        this.css("width", "auto");
                    }
                    if(option.autoHeight) {
                        scrollDiv.css("height", gridObj.parent().height() - 60);
                    //如果为自适应内容高度
                    }else if(option.autoContentHeight){
                        scrollDiv.css("height","auto");
                    }

                    //清除当前控件已绑定窗体响应事件
                    if (option.gridCache && option.gridCache.event && option.gridCache.event.autoWHResize) {
                        $(window).unbind("resize", option.gridCache.event.autoWHResize);
                    }


                    option.gridCache = {
                        event: {
                            autoWHResize: function () {
                                if (option.autoWidth) {
                                    rowContent.attr("width", rowContent.parent().width() - 2);
                                    content.css("width", "auto");
                                }
                                if(option.autoHeight){
                                    // setTimeout(function(){
                                        scrollDiv.css("height",gridObj.parent().height()-60);
                                    // },1);
                                }else if(option.autoContentHeight){
                                        scrollDiv.css("height","auto");
                                }

                            }
                        }
                    };

                    $(window).bind("resize", option.gridCache.event.autoWHResize);

                }
                // 添加表头
               // this.append(headTable);
                //添加内容容器
                this.append(scrollDiv);
                // 获取存在的属性定义
                for (var attr in option) {
                    if (attr == "title") {
                        var title = $("<div style='width:100%'  id='" + this.attr("id")
                            + "_WdfGrid_Title" + "'>" + option.title
                            + "</div>");
                        title.addClass("WdfGrid_Title");
                        headTable.before(title);
                    } else if (attr == "className") {
                        this.addClass(option.className);
                    }
                    else if (attr == "height") {

                    }
                    /*else if (attr == "width") {
                     if(option.autoWidth&&option.autoWidth==true){
                     this.css("width", "auto");
                     }
                     else{
                     this.css("width", option.width);
                     }
                     }  else if (attr == "autoWidth") {
                     if (option.autoWidth) {
                     this.css("width", "auto");
                     }
                     }*/
                    else if (attr == "columns") {

                        createColumn(option, headTable, this);
                    }

                }


                if (!option.autoHeight) {

                } else {
                    option.gridCache.event.autoWHResize();
                }
                //option.param={"pageInfo.curPage":1,"pageInfo.totalPages":0,"pageInfo.pageSize":$("#"+this.attr("id")+"_WdfGrid_Page").find("#pageRowCountLi").find("select").val()};

                var objGrid = this;
                // if (!option.url)
                //     return;

                //延迟数据加载处理
                if (option.delayLoad) {
                    setTimeout(function () {
                        query(option, objGrid);
                    }, option.delayLoad);
                } else {
                    query(option, this);
                }
            }

            else if (operate == "reload") {
                this.data("reqResult",null);
                if (option.keepPage&&!option.isNotPage) {
                    var thispage = this.find(".curPageHid").val();//保持当前页
                    getPageQuery(this,option,thispage);
                    delete option.keepPage;
                }else{
                    query(option, this);
                }

            }

            else if (operate == "getSelRows") {
                var rowDatas = [];
                var newRowDatas=[];
                this.find(".colCheckBox:checked").parent().parent().each(function (i) {
                    rowDatas.push($(this).data("rowData"));
                });
                if(rowDatas&&rowDatas.length>0){
                	for(var i=rowDatas.length-1;i>=0;i--){
                		newRowDatas.push(rowDatas[i]);
                	}
                }
                return newRowDatas;
            }else if(operate == "getSelRowObjs"){
                var rowObjs = [];
                this.find(".colCheckBox:checked").parent().parent().each(function (i, obj) {
                    rowObjs.push($(obj));

                });
                return rowObjs;
            }

            else if (operate == "getNotSelRows") {
                var rowDatas = [];
                this.find(".colCheckBox").not(".colCheckBox:checked").parent().parent().each(function (i) {
                    rowDatas.push($(this).data("rowData"));
                });
                return rowDatas;
            }

            //根据对象字段获取数据
            else if (operate == "getRowDatasByDK") {
                var rowDatas = [];
                this.find(".gridRow").each(function (i, obj) {
                    var data = $(obj).data("rowData");
                    if (data[option.key] && data[option.key] == option.value) {
                        rowDatas.push(data);
                    }
                });
                return rowDatas;
            }
            //根据对象字段获取数据
            else if (operate == "getRowsByDK") {
                var rows = [];
                this.find(".gridRow").each(function (i, obj) {
                    var data = $(obj).data("rowData");
                    if (data[option.key] && data[option.key] == option.value) {
                        rows.push($(obj));
                    }
                });
                return rows;
            }
            //获取所有行对象
            else if (operate == "getAllRowObjs") {

                var rowObjs = [];
                this.find(".gridRow").each(function (i, obj) {
                    rowObjs.push($(obj));
                });
                return rowObjs;

            }
            //获取所有行数据
            else if (operate == "getAllRows") {
                var rows = [];
                this.find(".gridRow").each(function (i, obj) {
                    var data = $(obj).data("rowData");
                   
                        rows.push(data);
                    
                });
                return rows;
            }
            //获取指定编辑行的输入框
            else if (operate == "getEditInput") {

                return function(rowObj,id){
                    return rowObj.find("input[id^="+id+"_wdfGridEditRowSel]");
                }

            }
            //编辑行
            else if (operate == "editRows") {
            	var gridObj=$(this);
            	
            	function colFormatter(colOpt,colContent,rowData,rowTr,rowTd,inputObj,isCancelEdit,isEdit){
            		 //如果自定义格式化
                    if (colOpt.formatter) {
                        if (colOpt.isFmtHtml) {
                            colContent.html(colOpt.formatter(rowData[colOpt.name], rowData, rowTr, rowTd,null,isCancelEdit,isEdit));
                            colContent.children().data("rowData",rowData);
                            colContent.attr("title", colContent.text());
                        } 
                        else if(colOpt.isFmtJqueryObj){
                      	  var formatters=colOpt.formatter(rowData[colOpt.name], rowData, rowTr, rowTd,null,isCancelEdit,isEdit);
                      	  //alert(Object.prototype.toString.call(formatters));
                      	  if(formatters&&Object.prototype.toString.call(formatters)=='[object Array]'){
                      		  for(var formatter in formatters){
                      			  var $formatter=$(formatters[formatter]);
                      			  $formatter.bind("rowData",rowData);
                              	  colContent.append($formatter);
                                  colContent.attr("title", colContent.text());
                      		  }
                      		
                      	  }else if(formatters){
                      		  var $formatters=$(formatters);
                      		  $formatters.bind("rowData",rowData);
                          	  colContent.append($formatters);
                              colContent.attr("title", colContent.text());  
                      	  }
                      	 
                        }
                        else {
                            //编辑模式下的格式化支持
                            if(!inputObj){
                                colContent.text(colOpt.formatter(rowData[colOpt.name], rowData, rowTr, rowTd,null,isCancelEdit,isEdit));
                                colContent.attr("title", colContent.text());
                            }else{
                                inputObj.val(colOpt.formatter(rowData[colOpt.name], rowData, rowTr, rowTd,null,isCancelEdit,isEdit));
                                colContent.append(inputObj);
                                colContent.attr("title", colContent.text());
                            }

                        }
                    } else {
                        colContent.attr("title", rowData[colOpt.name]);
                        colContent.html(rowData[colOpt.name]);
                    }
            	}
            	
               return function switchToEdit(editRows,isSave,isOnlyVal){
                    //以编辑行循环
                for(var k in editRows){
                    
                	var editRow=$(editRows[k]);
                	var editorCols=editRow.find(".editorCol");
                	var columns=option.columns;
                	var inputID="wdfGridEditRowSel_"+new UUID();
                	var colIndex=0;
                	var i2=0;
                	var triggerEvents=[];
                	
                	if(isSave){
                		var valOpts=[];
                		$(editorCols).each(function(i,obj){
                			var valOpt=$(obj).find("input[type=text]").data("valOpt");
                			if(valOpt)
                				valOpts.push(valOpt);
                		});
                		
                		if(!executeVal(valOpts))
                			return false;

                	}
                	
                	//以编辑列循环
                	for (var i1=0;i1<editorCols.length;i1++){
                		var editorCol=$(editorCols[i1]);
                		var div=editorCol.find("div");
                		
                		for (i2;i2<columns.length;i2++){
                			var col=columns[i2];
                			
                			if(col.isEdit&&colIndex==i1){
                    		  
                  			  var rowData=editRow.data("rowData");
                  			  var editor=col.editor;
                  			  
                            	  if(editor){
                            		  
                            	      function getValOpt(valOpt){
                            	    	var opt={};
                            	  		$.extend(true,opt,valOpt);
                            	    	return opt
                            	      } 
                            		  
                            		  
                            		  if(editor.inputType=="text"){
                            			  
                            			 if(!isSave){
                                            if(editor.maxLen){
                                                var textInput=$("<input autocomplete='off' class='_Text_Grid' maxlength='"+editor.maxLen+"' type='text'  id='"+editor.inputID+"_"+inputID+"' name='"+editor.inputName+"' style='width:80%' />");
                                            }else{
                                                var textInput=$("<input autocomplete='off' class='_Text_Grid' type='text'  id='"+editor.inputID+"_"+inputID+"' name='"+editor.inputName+"' style='width:80%' />");
                                            }

                            			  function getEvent(event,rowData,inputObj,curRow,gridObj){
                            			   return function(e){
                            				   event(curRow,rowData,inputObj,gridObj,e);
                            			   }
                            			  }
                            			  if(editor.onKeyDown){
                            				  var curRow=editRow;
                            				  textInput.bind("keydown",getEvent(editor.onKeyDown,curRow.data("rowData"),textInput,curRow,gridObj));
                            			  }
                                             if(editor.onClick){
                                                 var curRow=editRow;
                                                 textInput.bind("click",getEvent(editor.onClick,curRow.data("rowData"),textInput,curRow,gridObj));
                                             }
                            			  if(editor.onChange){
                            				  var curRow=editRow;
                            				  textInput.bind("change",getEvent(editor.onChange,curRow.data("rowData"),textInput,curRow,gridObj));
                            			  }
                            			  if(editor.valOpt){
                        					  
                        					  editor.valOpt.inputname=textInput.attr("id");
                        					  editor.valOpt.msgType="EditGridRowMsg";
                        					  textInput.data("valOpt",getValOpt(editor.valOpt));
                        					  
                        				  }
                            			  textInput.data("gridRowObj",editRow);
                            			  div.empty();
                                          //编辑模式下的格式化支持
                            			  if(col.editor.isFormatter){
                                              colFormatter(col,div,rowData,editRow,editorCol,textInput,null,true);
                                          }else{
                                              div.append(textInput);
                                              textInput.val(rowData[col.name]);
                                          }


                                             if(editor.isMyDate97){
                                                 textInput.attr("onFocus",editor.myDate97Fouce);
                                                 textInput.addClass("Wdate");
                                                 textInput.css({
                                                     "background-position-x":"right",
                                                     "background-position-y":-1
                                                 })
                                             }

                            			 }else if(isSave&&!isOnlyVal){
                            				 rowData[col.name]=div.find("input[type=text]").val();
                            				 div.empty();
                            				 if(col.formatter){
                            				 colFormatter(col,div,rowData,editRow,editorCol,null,true);
                            				 }else{
                            				 div.text(rowData[col.name]);
                            				 div.attr("title",rowData[col.name]);
                            				 }
                            				 //editRow.data("rowData",rowData);
                            			 }
                            			  
                            		  }else if(editor.inputType=="comSel"){
                            			  if(!isSave){
                            			  var textInput=$("<input autocomplete='off' class='_ComSel_Grid' type='text' id='"+editor.inputID+"_"+inputID+"' style='width:80%' />");
                            			  //当前行上绑定动态生成的输入框id后缀
                            			  editRow.data("inputID",inputID);
                            			  function getEvent(event,curRow,rowData,inputObj,curRow,gridObj){
                               			   return function(){
                               				   event(curRow,rowData,inputObj,curRow,gridObj);
                               			   }
                               			  }
                               			  if(editor.onKeyDown){
                               				  var curRow=editRow;
                               				  textInput.bind("keydown",getEvent(editor.onKeyDown,curRow.data("rowData"),textInput,curRow,gridObj));
                               			  }
                            			  textInput.data("gridRowObj",editRow);
                            			  div.empty();
                            			  div.append(textInput);
                            			  editor.comSelOpt.valInput.id=editor.inputID+"_"+inputID+"_InputVal";
                            			  editor.comSelOpt.id=editor.inputID+"_"+inputID;
                            			  editor.comSelOpt["isInitBindData"]=false;
                                           //生成输入框聚焦事件,对输入框进行下拉控件绑定。
                                           var getFocusEvent=function(editor){
                                               var newEditor={};
                                               $.extend(true,newEditor,editor);
                                               return function(){
                                                   if($("#"+newEditor.comSelOpt.id+"_WdfSel_SelPanel").length==0){
                                                       $(this).wdfSel("init",newEditor.comSelOpt);
                                                   }
                                               }
                                           };

                            			  function initLoadSel(editor,textInput) {
                                              var newEditor={};
                                              $.extend(true,newEditor,editor);
                                              $(textInput).wdfSel("init",newEditor.comSelOpt);
                                          }

                                              if(editor.isTrigger&&editor.isTrigger=="change"){
                                                  triggerEvents.push({eventType:"change",obj:textInput});
                                              }
                                              if(editor.initLoad == true){
                                                  initLoadSel(editor,textInput);
                                              }else{
                                                  textInput.bind("focus", getFocusEvent(editor));
                                              }

                                              //编辑模式下的格式化化支持
                                              if(col.editor.isFormatter){
                                                  colFormatter(col,div,rowData,editRow,editorCol,textInput,null,true);
                                              }else{
                                                  div.append(textInput);
                                                  textInput.val(rowData[editor.nameKey]);
                                              }
                                              if (editor.isInitSel) {
                                                  setTimeout(function(){
                                                      textInput.focus();
                                                  },100);
                                              }

                                          //如果输入框有值，则触发聚焦事件，绑定下拉控件。
                            			  if(textInput.val()&&textInput.val()!=""&&!editor.isInitSel)
                                              textInput.focus();
                            			  if($("body").find("#"+ editor.comSelOpt.valInput.id).length<1){
                            				  $("<input type='hidden' id='"+ editor.comSelOpt.valInput.id +"' />").appendTo(div);
                            			  }
                            			  
                            			  $("#"+editor.inputID+"_"+inputID+"_InputVal").val(rowData[editor.valKey]);

                            			  if(editor.valOpt){
                        					  editor.valOpt.inputname=textInput.attr("id");
                        					  editor.valOpt.msgType="EditGridRowMsg";//输入框的验证消息类型，这里为表格行编辑。
                        					  textInput.data("valOpt",getValOpt(editor.valOpt));
                        				  }
                            			  }else if(isSave&&!isOnlyVal){
                             				rowData[editor.nameKey]=div.find("input[type=text]").val();
                             				rowData[editor.valKey]=div.find("input[type=hidden]").val();
                             				div.empty();
                             				if(col.formatter){
                               				 colFormatter(col,div,rowData,editRow,editorCol,null,true);
                               				 }else{
                               				 div.text(rowData[editor.nameKey]);
                               				 div.attr("title",rowData[editor.nameKey]);
                               				 }
                               				 //删除该编辑行动态生成的下拉元素
                                              $("div[id*="+editRow.data("inputID")+"]").remove();
                             			 }
                            		  }
                  				
                            	  }
                  				colIndex++
                  				i2++;
                  				break;
                  			}
                		}
                	}
                	
                	$(triggerEvents).each(function(){
                		this.obj.triggerHandler(this.eventType);
                	});
                	
                	}
                return gridObj;
                };
                
             

            }
            //添加行
            else if (operate == "addRows") {
            	var gridObj=$(this);
            	var rowContent=gridObj.find(".WdfGrid_RowContent");
            	return function(rowData,isAsc,isNotTriggerLoaded){
            		createRow(rowData, option, rowContent, gridObj,true,isAsc,isNotTriggerLoaded);
            	}
            } 
            //删除行
            else if (operate == "removeRows") {
            	var gridObj=$(this);
            	var rowContent=gridObj.find(".WdfGrid_RowContent");
            	return function(rowObjs){
            		
            		$(rowObjs).each(function(i,rowObj){
            			var rowNo=$(rowObj).find(".rowNo");
            			if(rowNo.length>0){
            				var curNo=parseInt($(rowNo).text());
            				var rowNos=rowContent.find(".rowNo");
            				$(rowNos).each(function(){
            					var no=parseInt($(this).text());
            					if(no>curNo&&no>1){
            						no--;
            						$(rowNo).text(no);
            					}
            				});
            				
            				
            			}
            			if(rowObj.data("inputID"))
                            $("div[id*="+rowObj.data("inputID")+"]").remove();

            			$(rowObj).remove();

            		});
            		
            	}
            }
            //清空行
            else if (operate == "clearRows") {
            	$(this).find("tbody").empty();
            } 
            return this;
        }
    });
    //生成行
    function createRow(rowData, option, rowContent, gridObj, isAdd, isAsc,isNotTriggerLoaded) {
    	if(!isAdd){
            rowContent.find("tbody").html("");
        }
    	//var rowObjs=[];
    	if(rowData&&rowData.length>0){
    		var index={
    			i:0	
    		};
    		createRow(rowData,index,option,rowContent,gridObj);
    	}else{
    		wdfGridProgress("数据加载完成", gridObj);
            if (option.event && option.event.loaded&&!isNotTriggerLoaded) {
                option.event.loaded(option, gridObj, rowData);
            }
            setTimeout(function () {
                wdfGridProgRemove(gridObj);
            }, 300);
    	}
    	
            function createRow(rowData,index,option,rowContent,gridObj){
            	
            	var i=index.i;
            	
            	  var rowTr = $("<tr id='" + gridObj.attr("id") + "_WdfGrid_Row_" + new UUID()
                  + "'></tr>");
             //rowObjs.push(rowTr);
             if(!isAdd||isAsc){
             if (i % 2 == 0) {
                  rowTr.addClass("WdfGrid_Row_Even");
                  rowTr.addClass("gridRow");
              } else {
                  rowTr.addClass("WdfGrid_Row_Odd");
                  rowTr.addClass("gridRow");
              }
             }else{
            	 var no = gridObj.find(".gridRow").length+1;
            	 if (no % 2 == 0) {
                     rowTr.addClass("WdfGrid_Row_Even");
                     rowTr.addClass("gridRow");
                 } else {
                     rowTr.addClass("WdfGrid_Row_Odd");
                     rowTr.addClass("gridRow");
                 }
             }

              //默认生成行编号列
              if (option.isRowNo == undefined || option.isRowNo) {
                  var colNo = $("<td   class='colTd rowNo' nowrap='nowrap' style='white-space:nowrap'></td>");
                  colNo.css("width", "1%");
                  rowTr.append(colNo);
                  var curPage = parseInt(gridObj.find(".curPageHid").val());
                  var rowCount = screenPageSize;
                  var no = 1;
                  if (curPage && rowCount && !isAdd) {
                      no = (curPage - 1) * rowCount + (i + 1);
                  } else {
                	  if(gridObj.find(".rowNo").length==0){
                      no=1;
                	  }else{
                		  
                	    gridObj.find(".rowNo").each(function(i,obj){
                		  var colNum=parseInt($(obj).text());
                		  if(colNum>no)
                			  no=colNum
                	  });
                	  no++;
                	  }
                  }
                  colNo.html("<div>" + no + "</div>");
                  colNo.attr("title", no);
              }

              //如果开启选中按钮则在行首添加选中按钮列
              if (option.checkbox) {
                  var col = $("<td id='" + gridObj.attr("id") + "_WdfGrid_ColTd"
                      + "_CheckBox' class='colTd'></td>");
                  col.css("width", "1%");
                  var checkBox = $("<input type='checkbox' id='"
                      + gridObj.attr("id") + "_WdfGrid_"
                      + "CheckBox' class='colCheckBox'>");
                  //如果不支持多选添加多选排斥处理
                  if (!option.isMulitCheck) {
                      checkBox.bind("click", function (e) {
                          if (this.checked)
                              $("#" + gridObj.attr("id")).find(".colCheckBox").not(this).attr("checked", false);
                          
                          stopBubble(e);
                      });
                  }else{
                      checkBox.bind("click", function (e) {
                          stopPropagation(e)
                      });
                  }
                  col.append(checkBox);
                  rowTr.append(col);
                  
                  // if(option.event&&option.event.onCheckChange){
                 	//  checkBox.change(function(){
                 	// 	 option.event.onCheckChange(rowData,$(this),gridObj);
                 	//  });
                 	
                // }
                  
              }

              $(option.columns).each(
                  function (i1) {
                      //如果隐藏该列存在，隐藏该列
                      if (this.hidden && this.hidden == true) {
                          return;
                      }
                      //如果有列显示前回调函数，并且返回假，则该列不显示
                      if (this.onShow && !this.onShow()) {
                          return;
                      }
                      var rowTd = $("<td id='" + this.name
                          + "' nowrap='nowrap'></td>");
                      if (option.autoWidth && !option.colFixed) {
                          if (this.isBtnColumn) {
                              rowTd.css({
                                  "width": getPercent(option.columns, this.width) + "%"

                              });
                          } else {
                              rowTd.css({
                                  "width": getPercent(option.columns, this.width) + "%",
                                  "white-space" : "nowrap"
                              });
                          }

                      }
                      else {
                          if (this.isBtnColumn) {
                              rowTd.css({
                                  "width": this.width + "px"

                              });
                          } else {
                              rowTd.css({
                                  "width": this.width + "px",
                                  "white-space" : "nowrap"
                              });
                          }

                      }
                      //如果存在内容水平布局属性
                      if (this.align) {
                          rowTd.css({
                              "text-align": this.align
                          });
                      }

                      var div = $("<div></div>");
                      rowTd.append(div);
                      rowTd.addClass("WdfGrid_RowTd");
                      //级联对象取值处理
                      if (this.name.indexOf(".") != -1) {
                          var keys = this.name.split(".");
                          fillValue(div, rowData[i], keys, 0, keys.length, this.formatter);
                      }
                      //如果是按钮功能列
                      else if (this.isBtnColumn) {
                          var btns;
                          if (this.formatBtn) {
                              var curBtns = [];
                              $(this.buttons).each(function (i) {

                                  var btn = {
                                      id: this.id,
                                      label: this.label,
                                      className: this.className,
                                      hidden: this.hidden,
                                      click: this.click
                                  };
                                  curBtns.push(btn);

                              });

                              btns = this.formatBtn(rowData[i], curBtns, gridObj);

                          }
                          else {
                              btns = this.buttons;
                          }
                          var isfirstHidden = false;
                          for (var i2 = 0; i2 < btns.length; i2++) {

                              if (btns[i2].hidden) {
                                  if (i2 == 0) {
                                      isfirstHidden = true;
                                  }
                                  continue;
                              }

                              var aBtn = $("<a></a>");
                              aBtn.attr("id", btns[i2].id);
                              aBtn.attr("class", btns[i2].className);
                              if(btns[i2].href)
                              {
                              	aBtn.attr("href", btns[i2].href);
                              }
                              if(btns[i2].target)
                              {
                              	aBtn.attr("target", btns[i2].target);
                              }
                              if (i2 > 0 && !isfirstHidden) {
                                  aBtn.attr("style", "margin-left:10px");
                              } else {
                                  isfirstHidden = false;
                              }
                              isPrevHidden = false;
                              aBtn.html(btns[i2].label);
                              var clickEvent = getBtnClick(rowData[i], btns[i2].click, gridObj);
                              aBtn.bind("click",clickEvent);
                              rowTd.append(aBtn);
                          }
                          rowTd.removeAttr("nowrap");

                      }

                      //如果是子表操作列
                      else if (this.isSubColumn) {
                          var subGridOpt=this.gridOpt;
                          var columnOpt=this;
                          rowTd.css({
                              "width": this.width
                          });
                          rowTd.html("<div>+</div>");
                          rowTd.addClass("WdfGrid_RowTd");
                          function createSubTr(){
                              if(rowTd.data("subGrid")&&rowTd.text()=="-"){
                                  rowTd.data("subGrid").remove();
                                  rowTd.html("<div>+</div>");
                                  rowTd.parent("tr").removeClass("subTr");
                                  return;
                              }
                              var subTr=$("<tr></tr>")
                              rowTr.after(subTr);
                              var colSpanNum=1;
                              $(option.columns).each(function(i,column){
                                  if(column.hidden)
                                      return;
                                  colSpanNum++;
                              });
                              if(option.checkbox)
                                  colSpanNum++;
                              /*if(option.isRowNo) {
                                  colSpanNum++
                              }*/
                              var subTd=$("<td class='colTd subTd_Box' colspan='"+colSpanNum+"'></td>").appendTo(subTr);
                              rowTd.html("<div>-</div>");
                              rowTd.parent("tr").addClass("subTr");
                              var subGridId=rowTr.attr("id")+"_SubGrid";
                              var subGrid=$("<div id="+subGridId+"></div>").appendTo(subTd);
                              subGridOpt.id=subGridId;
                              var rowData=rowTr.data("rowData");
                              if(columnOpt.getParams){
                                  subGridOpt.param=columnOpt.getParams(rowData);
                              }
                              subGrid.wdfGrid("init",subGridOpt);
                              rowTd.data("subGrid",subTr);
                          }
                          rowTd.bind("click", getCellClick(rowData[i], rowTr, rowTd,createSubTr));


                      }
                      else {
                          //如果自定义格式化
                          var formatters = "";
                          if (this.formatter) {
                              if (this.isFmtHtml) {
                                  div.html(this.formatter(rowData[i][this.name], rowData[i], rowTr, rowTd,isAdd));
                                  div.children().data("rowData",rowData[i]);
                                  div.attr("title", div.text());
                                 
                              } 
                              else if(this.isFmtJqueryObj){
                            	   formatters=this.formatter(rowData[i][this.name], rowData[i], rowTr, rowTd,isAdd);

                            	  if(formatters&&Object.prototype.toString.call(formatters)=='[object Array]'){
                            		  for(var formatter in formatters){
                            			  var $formatter=$(formatters[formatter]);
                            			  $formatter.bind("rowData",rowData);
                                    	  div.append($formatter);
                                          //div.attr("title", div.text());
                                    	  $formatter.attr("title",$formatter.text());
                            		  }
                            		 
                            	  }else if(formatters){
                            		  var $formatters=$(formatters);
                            		  $formatters.bind("rowData",rowData);
                                	  div.append($formatters);
                                      //div.attr("title", div.text());
                                	  $formatters.attr("title",$formatters.text());
                            	  }
                            	 
                              }
                              else{

                                  div.text(this.formatter(rowData[i][this.name], rowData[i], rowTr, rowTd,isAdd));
                                  div.attr("title", div.text());
                              }

                          } else {
                              div.attr("title", rowData[i][this.name]);
                              div.html(rowData[i][this.name]);
                          }
                      }
                      if (rowTd){
                              rowTr.append(rowTd);
                              if(this.isEdit)
                                  rowTd.addClass("editorCol");


                      }
                      
                  });
              //如果存在行单击事件
              if (option.event && option.event.onRowClick) {
                  rowTr.bind("click", getRowClick(rowData[i], option.event.onRowClick, rowTr));
              }
              rowTr.data("rowData", rowData[i]);
              
              // rowTr.bind("click",function(){
              //     rowContent.find("tr").removeClass("clickFocus");
              //     $(this).addClass("clickFocus");
              // });
             if(!isAdd||isAsc){
                rowContent.append(rowTr);
             }else{
            	 var firstRow=rowContent.find("tbody").find("tr:first");
            	 if(firstRow.length>0){
            		 firstRow.before(rowTr);
            	 }else{
            		 rowContent.append(rowTr);
            	
            	 }
             }
                   /* rowTr.addClass("rotate");
                    if(true){
                    rowTr.addClass("leftIn");
                    }else{
                    rowTr.addClass("rotate");
                    }
                    setTimeout(function(){
                    	//rowTr.removeClass("rotate");
                    	 if(true){
                    	    //rowTr.removeClass("leftIn");
                    	 }else{
                    		 //rowTr.removeClass("rotate");
                    	 }
                    },1000);*/
             
             if (option.event && option.event.rowAdded) {
                 option.event.rowAdded(option, gridObj, rowData[index.i]);
             }
                if(option.event && option.event.onRowMouse){
                    var timeOutMouse;
                    rowTr.bind("mouseenter",function () {
                        var btns = option.event.onRowMouse(rowData[i],gridObj);
                        if(btns.length>0){
                            clearTimeout(timeOutMouse);
                            var trLeft = $(this).offset().left+"px";
                            var trTop = $(this).offset().top+$(this).height()+"px";
                            timeOutMouse = setTimeout(function () {
                                $("#"+option.id+"_mousePanel").remove();
                                var mousePannl = $("<div id='"+option.id+"_mousePanel' class='mousePannl_Content'></div>").appendTo("body");
                                for (var i=0;i<btns.length;i++){
                                    btns[i].appendTo(mousePannl);
                                }
                                mousePannl.css("left",trLeft);
                                mousePannl.css("top",trTop);
                                mousePannl.bind("mouseenter",function () {

                                    clearTimeout(timeOutMouse);

                                    //e.stopPropagation();
                                });
                                mousePannl.bind("mouseleave",function () {
                                    clearTimeout(timeOutMouse);
                                    timeOutMouse = setTimeout(function () {
                                        $("#"+option.id+"_mousePanel").remove();
                                    },300);
                                })
                            },500);
                        }


                    });
                    rowTr.bind("mouseleave",function () {
                        clearTimeout(timeOutMouse);
                        timeOutMouse = setTimeout(function () {
                            $("#"+option.id+"_mousePanel").remove();
                        },500);
                    });
                }
                index.i++;
                    if(index.i<rowData.length){
                    	// setTimeout(function(){
                    	    if(isAdd){
                    		gridObj.wdfGrid("editRows",option)([createRow(rowData,index,option,rowContent,gridObj)]);
                    	    }else{
                    	    createRow(rowData,index,option,rowContent,gridObj);
                    	    }
                    	// },1);
                    	}else{
                    		if (option.event && option.event.loaded&&!isNotTriggerLoaded) {
                                option.event.loaded(option, gridObj, rowData);
                            }
                    		/*if(basePath){
                    			$.getScript(basePath+"resource/plugins/wdfjslib/tableWidthResize.js",function(){
                    				gridObj.find("table").resizableColumns({});
                    			});
                    			}*/
                        gridObj.find("table").resizableColumns({});
                        gridObj.find(".wdfGridProgress_loadingImg").text("数据加载完成");
                        if(!option.isSubGrid){
                      //      gridObj.find(".WdfGrid_ScrollDiv").css("height",40*screenPageSize+40+"px");
                        }
                        setTimeout(function () {
                            // gridObj.find(".WdfGrid_ScrollDiv").css("height",gridObj.find(".WdfGrid_ScrollDiv").height()+"px");
                            wdfGridProgRemove(gridObj);
                        }, 300);


                      /*  if(option.autoHeight){
                            $(window).on('resize', function () {
                                gridObj.find(".WdfGrid_ScrollDiv").eq(0).css("height",($("body").height()-300)+"px");
                            }).resize();
                        }else{
                            gridObj.find(".WdfGrid_ScrollDiv").css("height","auto");
                        }*/

                    	}
                    
                    if(isAdd){
                		gridObj.wdfGrid("editRows",option)([rowTr]);
                	    }
                    
            return rowTr;	
            }
        setTimeout(function () {

            isreload  = 1;

        }, 300);
    	//return rowObjs;
        }
    
        //返回按钮单击事件
        function getBtnClick(rowData, event, gridObj) {

            return function () {
                event(rowData, gridObj);
                stopBubble(event);
            };

        };
    

    //返回行单击事件
    function getRowClick(rowData, event, rowTr) {
        return function () {
            event(rowData, rowTr);
        };

    }

    //返回表格点击事件
    function getCellClick(rowData, rowTr, cell, event) {
        return function () {
            event(rowData, rowTr, cell);
        };

    }


    //生成列
    function createColumn(option, headTable, gridObj) {

        //默认生成行编号列
        if (option.isRowNo == undefined || option.isRowNo) {
            var colNo = $("<th  class='colTd' id='colNo' nowrap='nowrap'></th>");
            colNo.css("width", "2%");
            headTable.append(colNo);
        }

        $(option.columns).each(
            function (i) {

                if (option.checkbox && i == 0) {
                    var col = $("<th id='" + gridObj.attr("id")
                        + "_WdfGrid_ColTd"
                        + "_CheckBox' class='colTd'></th>");
                    col.css("width", "2%");
                    headTable.append(col);
                    //如果支持多选则添加多选按钮
                    if (option.isMulitCheck) {

                        var checkBox = $("<input type='checkbox' id='"
                            + gridObj.attr("id") + "_WdfGrid_"
                            + "CheckBoxAll' class='colCheckBoxAll'>");

                        col.append(checkBox);
                        checkBox.bind("click", function () {

                            $("#" + gridObj.attr("id") + "_WdfGrid_RowContent")
                                .find(".colCheckBox").prop("checked",
                                this.checked);
                            var rows=gridObj.find(".WdfGrid_RowContent").find(".colCheckBox");
                            addMoveEffect(rows,{i:0});

                        });

                        function addMoveEffect(objs,index){
                        	var obj=$(objs[index.i]);
                        	obj.addClass("rightMove");
                        	setTimeout(function(){
                        		obj.removeClass("rightMove");
                        	},600);
                        	index.i++;
                        	if(index.i<objs.length){
                        		setTimeout(function(){
                        			addMoveEffect(objs,index);
                            	},50);
                        	}
                        }
                        
                    }

                }

                //隐藏标题列
                if (this.hidden && this.hidden == true)
                    return;
                //列显示前执行
                if (this.onShow && !this.onShow())
                    return;

                var col = $("<th id='" + gridObj.attr("id")
                    + "_WdfGrid_ColTd" + "_" + this.name
                    + "' class='colTd'></th>");
                for (var attr in this) {

                    if (attr == "label") {
                        col.html(this.label);
                    }

                    else if (attr == "width") {
                        if (option.autoWidth && !option.colFixed && !this.isSubColumn) {
                            col.css("width", getPercent(option.columns, this.width) + "%");
                        }
                        else if (this.isSubColumn) {
                            col.css("width",this.width);
                        }
                        else {
                            col.css("width",this.width );
                        }
                    }
                 if(attr=="order"){
                        //排序
                        if(this.order){
                            col.empty();
                            var orderContent=$("<div style='position:relative;width:100%;'></div>").appendTo(col);
                            orderContent.text(this.label);
                            var orderBtn=$("<div class='orderBtn orderDefaultBtn'></div>").appendTo(orderContent);
                            orderBtn.bind("click",function(){
                              var order=$(this).data("order");
                              order.orderType=order.orderType=="ASC"?"DESC":"ASC";
                              headTable.find(".orderBtn").removeAttr("class").addClass("orderBtn orderDisabledBtn");
                              if(order.orderType=="ASC"){
                                  $(this).attr("title","点击后按"+order.label+"进行倒序");
                                  $(this).removeAttr("class").addClass("orderBtn orderAscBtn");
                                }else{
                                    $(this).attr("title","点击后按"+order.label+"进行正序");
                                  $(this).removeAttr("class").addClass("orderBtn orderDescBtn");
                                }



                                createOrderData(option,order);
                                if(option.keepPage){
                                var thispage = gridObj.find(".curPageHid").val();//保持当前页
                                    getPageQuery(gridObj,option,thispage);

                                delete option.keepPage;
                                 }else{
                                    query(option,gridObj);
                                }
                            });
                            orderBtn.data("order",this.order);
                            if(this.order.orderType=="ASC"){
                                orderBtn.attr("title","点击后按"+this.order.label+"进行倒序");
                            }else{
                                orderBtn.attr("title","点击后按"+this.order.label+"进行正序");
                            }
                            createOrderData(option,this.order);
                        }
                 }
                }
                headTable.append(col);
                //col.css("cursor","move");
                col.css({
                "-webkit-user-select":"none",
                "-moz-user-select":"none",
                "-ms-user-select":"none",
                 "user-select":"none"
                });
           
            });

    }

    /**
     * 生成排序数据
     * wonderful 201805151209
     * @param option
     * @param order
     */
    function createOrderData(option,order){
        var orderType=order.orderType;
        var reverseType=orderType=="ASC"?"DESC":"ASC";
        var orderName=order.name;
        if(!option.orderData&&option.orderData!=""){
            option.orderData=new String("");
        }
        //去掉重复排序
        if( option.orderData.indexOf(orderName)!=-1){
                option.orderData=option.orderData.replace(orderName,"");
            }
        //如果该排序类型存在，则当前优先排序。
        if(option.orderData.indexOf(orderType)!=-1){
            option.orderData=orderName+" "+orderType+","+option.orderData;
        //如果当前排序类型不存，并且反向排序类型存在，当前优先排序。
        }else if(option.orderData.indexOf(orderType)==-1
            &&option.orderData.indexOf(reverseType)!=-1){
            option.orderData=orderName+" "+orderType+","+option.orderData;
            //如果当前排序以及反向排序类型不存在，则新增排序。
        }else if(option.orderData.indexOf(orderType)==-1
            &&option.orderData.indexOf(reverseType)==-1){
            option.orderData=orderName+" "+orderType;
        }
        //去冗余逗号，去冗余排序定义。
        option.orderData=option.orderData.replace(/^\s*,{1}/g,"");
        option.orderData=option.orderData.replace(/\,\s*\,/g,",");
        option.orderData=option.orderData.replace(/ASC\s*DESC/g,"ASC");
        option.orderData=option.orderData.replace(/DESC\s*ASC/g,"DESC");
        option.orderData=option.orderData.replace(/\,\s*DESC$/g,"");
        option.orderData=option.orderData.replace(/\,\s*ASC$/g,"");
        option.orderData=option.orderData.replace(/ASC\s*\,\s*DESC\s*\,/g,"ASC,");
        option.orderData=option.orderData.replace(/DESC\s*\,\s*ASC\s*\,/g,"DESC,");
        option.orderData=option.orderData.replace(/DESC\s*\,\s*DESC\s*\,/g,"DESC,");
        option.orderData=option.orderData.replace(/ASC\s*\,\s*ASC\s*\,/g,"ASC,");
        option.orderData=option.orderData.replace(/^\s*DESC\s*\,\\s*$/g,"");
        option.orderData=option.orderData.replace(/^\s*ASC\s*\,\\s*$/g,"");
    }

    /**
     * 获取级联对象属性值
     * params 行列对象,待填充的数据对象,用来索引数据的键对象集合,起始索引,键集合长度,格式函数
     *
     */
    function fillValue(rowTd, data, keys, index, len, formatter) {
        if (index == len) {
            if (formatter) {
                rowTd.attr("title", formatter(data));
                rowTd.html(formatter(data));
            } else {
                rowTd.attr("title", data);
                rowTd.html(data);
            }
            return;
        }
        if (data[keys[index]]) {
            fillValue(rowTd, data[keys[index]], keys, index + 1, len, formatter);
        }
    }

    //获取百分比
    function getPercent(columns, sub) {
        var total = 0;
        for (var i = 0; i < columns.length; i++) {
            if (columns[i].hidden)
                continue;
            if (columns[i].width) {
                total += parseInt(columns[i].width);
            }
            else {
                total += 80;
            }

        }

        var percent = (parseFloat(sub) / parseFloat(total)) * 100;
        return percent.toFixed(0);
    }

    //生成分页
    function createPage(gridObj,opt,pageInfo) {
        $("#"+ gridObj.attr("id") + "_WdfGrid_Page_box" ).remove();
        var pageDiv = $("<div id='" + gridObj.attr("id") + "_WdfGrid_Page_box' class='WdfGrid_Page_box'><div id='" + gridObj.attr("id") + "_WdfGrid_Page' class='WdfGrid_Page'></div></div>");
        var pageInfoCount = $("<input type='hidden' size='4' id='"+gridObj.attr("id")+"_WdfGrid_PageInfo' class='curPageHid'>");

        opt.pageInfo = pageInfo;
         gridObj.append(pageDiv);
        gridObj.append(pageInfo);
        pageInfoCount.val(pageInfo.curPage);
        gridObj.find("#"+gridObj.attr("id")+"_WdfGrid_PageInfo").remove();
        pageInfoCount.appendTo(gridObj);
        // $("#"+gridObj.attr("id") + "_WdfGrid_Page").pagination(  //分布总数量，必须参数
        //     {
        //         totalData:pageInfo.totalRows,
        //         showData:5,
        //         coping: true,
        //         callback:function (e) {
        //             if(e.getCurrent() == 0){
        //                 $("#" + gridObj.attr("id") + "_WdfGrid_Page").find("input").val(e.getCurrent()+1);
        //             }else{
        //                 $("#" + gridObj.attr("id") + "_WdfGrid_Page").find("input").val(e.getCurrent());
        //             }
        //
        //             getPageQuery(gridObj,opt,e.getCurrent());
        //         }
        //     });
        if(pageInfo.totalPages>1){
            $("#"+gridObj.attr("id") + "_WdfGrid_Page").pagination(pageInfo.totalRows, {
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                load_first_page:false,
                current_page: 0,
                callback: function (e) {
                    pageInfoCount.val(e+1);
                    getPageQuery(gridObj,opt,e+1);
                },
                items_per_page:screenPageSize //每页显示1项
            });
            $("#"+gridObj.attr("id") + "_WdfGrid_Page").show();
            //避免a标签刷新当前页
        }else{
            $("#"+gridObj.attr("id") + "_WdfGrid_Page").hide();
        }

    }

    //生成分页参数


    //查询数据
    function query(option,gridObj) {
        if(isreload == 0){
            return;
        }
        isreload = 0;
        if (option.event && option.event.readyLoad) {
            option.event.readyLoad(option, gridObj);
        }else{
            isreload = 1;
        }

        gridObj.find(".colCheckBoxAll").attr("checked", false);
        wdfGridProgress(option.loadMsg, gridObj);
        // if (option.keepPage&&!option.isNotPage) {
        //
        //
        //     delete option.keepPage;
        // }

        option = createParam(option,1);
        if(!option.url){
                if (option.event && option.event.dataFilter) {
                    option.event.dataFilter(data[option.root]);
                }
                createRow(option.gridData, option, $("#" + gridObj.attr("id") + "_WdfGrid_RowContent"), gridObj);

        }else{
            $.ajax({
                url: option.url,
                //processData: false,
                //data: xmlDocument,
                async: true,
                dataType: "json",
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
                data: option.param,
                beforeSend: null,
                success: function (data) {
                    gridObj.data("reqResult",data);
                    if(data.status==1){
                    if(option.root)
                        data.data=data[option.root];
                    if(data.data.length>0&&gridObj.parents(".wdfTab").size()>0){
                        gridObj.find(".gridShouqi_btn").show();
                        gridObj.find(".WdfGrid_ScrollDiv").show();
                    }else if(gridObj.parents(".wdfTab").size()>0){

                        gridObj.find(".gridZhankai_btn").show();

                    }
                    if(!option.isNotPage){
                        var wdfGridPage = {
                            curPage: data.pageInfo.curPage,//当前页
                            totalPages: data.pageInfo.totalPages,//总页数
                            totalRows: data.pageInfo.totalRows//总数据条数
                        };
                        createPage(gridObj,option,wdfGridPage);
                    }
                    if (data[option.root]) {
                        if (option.event && option.event.dataFilter) {
                            option.event.dataFilter(data[option.root]);
                        }
                        createRow(data[option.root], option, $("#" + gridObj.attr("id") + "_WdfGrid_RowContent"), gridObj);
                    }
                    else {
                        $("#" + gridObj.attr("id") + "_WdfGrid_RowContent").empty();
                    }
                    }else{
                        gridObj.find(".wdfGridProgress_loadingImg").text(data.msg?data.msg:"服务器异常！");
                        if (option.event && option.event.loaded) {
                            option.event.loaded(option, gridObj, rowData);
                        }
                        setTimeout(function () {
                            wdfGridProgRemove(gridObj);
                        }, 200);
                    }

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gridObj.find(".wdfGridProgress_loadingImg").text("服务器异常!");
                    setTimeout(function () {
                        wdfGridProgRemove(gridObj);
                    }, 1000);
                }
            });
        }
        var listener;
        //进度条加载
    }


    function createParam(option,curPage) {

        if(option.isNotPage){
            //装载排序参数
            if (option.param && (new String(option.param).indexOf("&") != -1 || new String(option.param).indexOf("=") != -1)) {
                if(new String(option.param).indexOf('orderData') != -1){
                    option.param = new String(option.param).replace(/orderData\=[\W\w]+/g, "orderData=" + option.orderData);
                } else {
                    if(option.orderData)
                        option.param+="&orderData="+option.orderData;
                }
            }else if(option.param==""){
                if(option.orderData)
                    option.param+="?orderData="+option.orderData;
            } else if (option.param) {
                if(option.orderData)
                option.param["orderData"]=option.orderData;
            }else {
                if(option.orderData)
                    option.param["orderData"]=option.orderData;
            }
            return option;
        }

        if (option.param && (new String(option.param).indexOf("&") != -1 || new String(option.param).indexOf("=") != -1)) {

            if (new String(option.param).indexOf('curPage') != -1) {
                option.param = new String(option.param).replace(/curPage\=[0-9]+/g, "curPage=" + curPage);
                option.param = new String(option.param).replace(/pageSize\=[0-9]+/g, "pageSize=" + screenPageSize);
            } else {
                option.param += "&curPage=" + curPage;
                option.param += "&pageSize="
                    + screenPageSize;

            }

            if(new String(option.param).indexOf('orderData') != -1){
                option.param = new String(option.param).replace(/orderData\=[\W\w]+/g, "orderData=" + option.orderData);
            } else {
                if(option.orderData)
                    option.param+="&orderData="+option.orderData;
            }

        }else if(option.param==""){
            option.param = "&curPage=" + curPage;
            option.param += "&pageSize="
                + screenPageSize;
            if(option.orderData)
                option.param+="&orderData="+option.orderData;
        }
        else if (option.param) {

            option.param["curPage"] = curPage;
            option.param["pageSize"] = screenPageSize;
            if(option.orderData)
                option.param["orderData"]=option.orderData;

        } else {
            option.param = {};
            option.param["curPage"] = curPage;
            option.param["pageSize"] = screenPageSize;
            if(option.orderData)
                option.param["orderData"]=option.orderData;
        }
        return option;
    }

    function getPageQuery(gridObj,option,curPage) {

        wdfGridProgress(option.loadMsg, gridObj);
        createParam(option,curPage);
        $.ajax({
            url: option.url,
            //processData: false,
            //data: xmlDocument,
            async: true,
            dataType: "json",
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            // data: encodeURI(option.param),//解决页面默认为GBK编码导致的Ajax传输中文乱码问题
            data: option.param,
            beforeSend: null,
            success: function (data) {
                if(data.status==1){
                if (data[option.root]) {
                    if (option.event && option.event.dataFilter) {
                        option.event.dataFilter(data[option.root]);
                    }
                    createRow(data[option.root], option, $("#" + gridObj.attr("id") + "_WdfGrid_RowContent"), gridObj);
                }
                else {
                    $("#" + gridObj.attr("id") + "_WdfGrid_RowContent").empty();
                }
                }else{
                    gridObj.find(".wdfGridProgress_loadingImg").text("服务器异常!");
                    if (option.event && option.event.loaded) {
                        option.event.loaded(option, gridObj, rowData);
                    }
                    setTimeout(function () {
                        wdfGridProgRemove(gridObj);
                    }, 300);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gridObj.find(".wdfGridProgress_loadingImg").text("服务器异常!");
                setTimeout(function () {
                    wdfGridProgRemove(gridObj);
                }, 1000);
            }
        });
    }


    function PageCallback() {

    }
    function wdfGridProgress(info, gridObj) {
       /* gridObj.find("div[id*='_wdfGridProgress']").remove();
        //$("#"+gridObj.attr("id")+"_wdfGridProgress_Prog").remove();
        //$("#"+gridObj.attr("id")+"_wdfGridProgress_Bg").remove();
        var progDiv = $("<div id='" + gridObj.attr("id") + "_wdfGridProgress_Prog' class='wdfGridProgress_Prog'><div/>");
        var msg = $("<span class='wdfGridProgress_loadingImg'>" + info + "</span>");
        var bgDiv = $("<div id='" + gridObj.attr("id") + "_wdfGridProgress_Bg' class='wdfGridProgress_Bg'><div/>");

        progDiv.append(msg);
        gridObj.append(progDiv);
        gridObj.append(bgDiv);

        var left = gridObj.width() / 2 - progDiv.width() / 2;
        var top = gridObj.height() / 2 - progDiv.height() / 2;
        progDiv.css({left: left, top:top});
        bgDiv.css({width:gridObj.width(),height:gridObj.height()});
        /!*var curWidth = bgDiv.width();
        var curHeight = bgDiv.height();*!/
        var curWidth = gridObj.width();
        var curHeight = gridObj.height();
        listener = function () {
            if (gridObj.width() != curWidth || gridObj.height() != curHeight) {
                var left = gridObj.width() / 2 - progDiv.width() / 2;
                var top = gridObj.height() / 2 - progDiv.height() / 2;
                // progDiv.css({left: left, top: top});
                curWidth = gridObj.width();
                curHeight = gridObj.height();
                bgDiv.css({width:gridObj.width(),height:gridObj.height()});
            }
        };
       window.setInterval(listener, 1);*/
    }

    //删除进度条
    function wdfGridProgRemove(gridObj) {
       /* window.clearTimeout(listener,1);
        gridObj.find("div[id*='_wdfGridProgress']").remove();*/
    }

    /******************************UUID生成********************************/

    // On creation of a UUID object, set it's initial value
    function UUID() {
        this.id = this.createUUID();
    }

    // When asked what this Object is, lie and return it's value
    UUID.prototype.valueOf = function () {
        return this.id;
    }
    UUID.prototype.toString = function () {
        return this.id;
    }

    //
    // INSTANCE SPECIFIC METHODS
    //

    UUID.prototype.createUUID = function () {
        //
        // Loose interpretation of the specification DCE 1.1: Remote Procedure Call
        // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
        // since JavaScript doesn't allow access to internal systems, the last 48 bits
        // of the node section is made up using a series of random numbers (6 octets long).
        //
        var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
        var dc = new Date();
        var t = dc.getTime() - dg.getTime();
        var h = '-';
        var tl = UUID.getIntegerBits(t, 0, 31);
        var tm = UUID.getIntegerBits(t, 32, 47);
        var thv = UUID.getIntegerBits(t, 48, 59) + '1'; // version 1, security version is 2
        var csar = UUID.getIntegerBits(UUID.rand(4095), 0, 7);
        var csl = UUID.getIntegerBits(UUID.rand(4095), 0, 7);

        // since detection of anything about the machine/browser is far to buggy,
        // include some more random numbers here
        // if NIC or an IP can be obtained reliably, that should be put in
        // here instead.
        var n = UUID.getIntegerBits(UUID.rand(8191), 0, 7) +
            UUID.getIntegerBits(UUID.rand(8191), 8, 15) +
            UUID.getIntegerBits(UUID.rand(8191), 0, 7) +
            UUID.getIntegerBits(UUID.rand(8191), 8, 15) +
            UUID.getIntegerBits(UUID.rand(8191), 0, 15); // this last number is two octets long
        return tl + h + tm + h + thv + h + csar + csl + h + n;
    }


    //
    // GENERAL METHODS (Not instance specific)
    //


    // Pull out only certain bits from a very large integer, used to get the time
    // code information for the first part of a UUID. Will return zero's if there
    // aren't enough bits to shift where it needs to.
    UUID.getIntegerBits = function (val, start, end) {
        var base16 = UUID.returnBase(val, 16);
        var quadArray = new Array();
        var quadString = '';
        var i = 0;
        for (i = 0; i < base16.length; i++) {
            quadArray.push(base16.substring(i, i + 1));
        }
        for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
            if (!quadArray[i] || quadArray[i] == '') quadString += '0';
            else quadString += quadArray[i];
        }
        return quadString;
    }

    // Numeric Base Conversion algorithm from irt.org
    // In base 16: 0=0, 5=5, 10=A, 15=F
    UUID.returnBase = function (number, base) {
        //
        // Copyright 1996-2006 irt.org, All Rights Reserved.
        //
        // Downloaded from: http://www.irt.org/script/146.htm
        // modified to work in this class by Erik Giberti
        var convert = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        if (number < base) var output = convert[number];
        else {
            var MSD = '' + Math.floor(number / base);
            var LSD = number - MSD * base;
            if (MSD >= base) var output = this.returnBase(MSD, base) + convert[LSD];
            else var output = convert[MSD] + convert[LSD];
        }
        return output;
    }

    // pick a random number within a range of numbers
    // int b rand(int a); where 0 <= b <= a
    UUID.rand = function (max) {
        return Math.floor(Math.random() * max);
    }

    // end of UUID class file
    /*************************************************************************/

})();





function slideScrollDiv(e) {
    $(e).hide();
    $(e).parent(".test").find(".WdfGrid_ScrollDiv").slideUp();
    $(e).parent(".test").find(".gridZhankai_btn").show();
}
function slideDownScrollDiv(e) {
    $(e).hide();
    $(e).parent(".test").find(".WdfGrid_ScrollDiv").slideDown();
    $(e).parent(".test").find(".gridShouqi_btn").show();
}